﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMSABL;
using WMSABL.SY;
using WMSAML.SY;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;

namespace ElectronicWMSA.SY
{
    public partial class RoleRMFrm : Form
    {
        #region
        public int _Roleid = 0;
        public int _Parent_id = 0;
        public string _strWhere = "";
        public string _groupidStrWhere = "";
        public string _RolePemsissionidStr = "";
        TUsers_BLL bll_TUsers = new TUsers_BLL();
        TRoles_BLL bll_TRoles = new TRoles_BLL();
        PublicDataSet bll_CommonPub = new PublicDataSet(); 
        TSystemRegistBLL bll_SystemRegist = new TSystemRegistBLL();
        TRolePermissionRelation_BLL bll_TRolePermissionRelation = new TRolePermissionRelation_BLL();
        public RoleRMFrm()
        {
            InitializeComponent();
            this._strWhere = "";
            this._Roleid = 0; 
            this.pageControlUserList.PageCurrent = 1;
            this.pageControlUserList.PageSize = 20;
            this.DBind();
        }
        #endregion
          
        #region  绑定
        public void DBind()
        {
            this.labShowSelectRole.BackColor = Color.Transparent;
            this.labShowTop.BackColor = Color.Transparent;
            this.DBind_Roles();
            this.DBindU();
            this.DBind_MenuMoudle();
            this.DBindPermisission();
        }
        #endregion

        #region 绑定角色
        public void DBind_Roles()
        {
            this.treeViewRoleList.Nodes.Clear();
            DataSet ds = new DataSet();
            ds = bll_CommonPub.GetDataSet("TRoles", "");
            DataTable dt = ds.Tables[0];
            TreeNode node = new TreeNode();
            node.Name = "0";
            node.Text = "角色列表";
            treeViewRoleList.Nodes.Add(node);
            this.AddNodes_Roles(dt, node);
            this.treeViewRoleList.ExpandAll();
            this.treeViewRoleList.SelectedNode = treeViewRoleList.TopNode; //最顶端节点选中
        }

        public void AddNodes_Roles(DataTable dt, TreeNode node)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "Parent_id='" + node.Name + "'";
            foreach (DataRowView row in dv)
            {
                TreeNode replyNode = new TreeNode();
                replyNode.Text = row["Role_name"].ToString();
                replyNode.Name = row["Role_id"].ToString();
                node.Nodes.Add(replyNode);
                this.AddNodes_Roles(dt, replyNode);
            }
        }

        /// <summary>
        /// 展开
        /// </summary>
        private void labExpansion_Click(object sender, EventArgs e)
        {
            this.treeViewRoleList.ExpandAll();
        }

        /// <summary>
        /// 折叠
        /// </summary>
        private void labFold_Click(object sender, EventArgs e)
        {
            this.treeViewRoleList.CollapseAll();
        }
        #endregion

        #region  绑定用户数据
        private int DBindU()
        {
            ElectronicWMSA.Comm.Forms.MsControls.PageData pageData = new ElectronicWMSA.Comm.Forms.MsControls.PageData();
            pageData.TableName = "Vlh_TUserListByRoleid";
            pageData.PrimaryKey = "User_id";
            pageData.OrderStr = "User_id";
            pageData.PageIndex = this.pageControlUserList.PageCurrent;
            pageData.PageSize = this.pageControlUserList.PageSize;
            pageData.QueryCondition = _strWhere;
            pageData.QueryFieldName = "*";

            this.pageControlUserList.bindingSource.DataSource = pageData.QueryDataTable().Tables[0];
            this.pageControlUserList.bindingNavigator.BindingSource = pageControlUserList.bindingSource;
            this.dataGridViewUserList.AutoGenerateColumns = false;
            this.dataGridViewUserList.DataSource = this.pageControlUserList.bindingSource;
            this.dataGridViewUserList.ClearSelection();
            return pageData.TotalCount;
        }

        private void dataGridViewUserList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(dataGridViewUserList.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dataGridViewUserList.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }

        private int pageControlUserList_EventPaging(ElectronicWMSA.Comm.Forms.MsControls.EventPagingArg e)
        {
            return this.DBindU();
        }
        #endregion

        #region 绑定权限
        public void DBind_MenuMoudle()
        {
            this.treeViewMenuPermission.Nodes.Clear();
            DataSet ds = new DataSet();
            ds = bll_SystemRegist.GetList_SystemMeun();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dv = new DataView(dt);
            dv.RowFilter = "headID=0";
            foreach (DataRowView drv in dv)
            {
                TreeNode node = new TreeNode();
                node.Text = drv["Menu_Name"].ToString();
                node.Name = drv["ID"].ToString();
                node.ImageIndex = 0;
                node.SelectedImageIndex = 0;
                this.treeViewMenuPermission.Nodes.Add(node);
                this.AddNodes(dt, node);
            }
            this.treeViewMenuPermission.Nodes[0].Expand();
        }
        public void AddNodes(DataTable dt, TreeNode node)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "headID='" + node.Name + "'";
            foreach (DataRowView row in dv)
            {
                TreeNode replyNode = new TreeNode();
                replyNode.Text = row["Menu_Name"].ToString();
                replyNode.Name = row["ID"].ToString();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 1;
                node.Nodes.Add(replyNode);
                AddNodes(dt, replyNode);
            }
        }
        /// <summary>
        /// 列表绑定
        /// </summary>
        public void DBindPermisission()
        {
            DataSet ds = new DataSet();
            ds = bll_CommonPub.GetDataSet("TDictionary_Category", " SortID=1 ");
            dataGridViewMoudlePermisissionList.DataSource = ds.Tables[0].DefaultView;
            this.dataGridViewMoudlePermisissionList.ClearSelection();
        }
        private void dataGridViewMoudlePermisissionList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
                this.dataGridViewMoudlePermisissionList.Rows[e.RowIndex].Selected = true;
        }
        #endregion

        #region 角色管理(增删改)

        #region 新增角色
        private void btnRoleAdd_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("新增")) return;

            string roleName = this.txtRoleAddName.Text.Trim();
            if (roleName == "")
            {
                this.labRoleAddShow.Text = "请填写角色名称！";
                this.txtRoleAddName.Focus();
                return;
            }
            if (bll_TRoles.ExistsByName(roleName))
            {
                this.labRoleAddShow.Text = "角色名称已存在！";
                this.txtRoleAddName.Focus();
                return;
            }
            TRoles_Entity entity = new TRoles_Entity();
            entity.Role_name = roleName;
            entity.Creat_time = DateTime.Now;
            entity.Description = txtRoleAddMark.Text.Trim();

            if (MessageClass.enquire("确认添加信息！") == DialogResult.OK)
            {
                if (bll_TRoles.Add(entity) > 0)
                {
                    MessageClass.right("成功！");
                    btnRoleClear_Click(sender, e);
                }
                else
                    MessageClass.error("失败！");
            }
        }
        #endregion

        #region 修改角色
        private void btnRoleUpdate_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("编辑")) return;

            TRoles_Entity entity = new TRoles_Entity();
            entity = bll_TRoles.GetEntityByID(_Roleid);
            if (entity == null)
            {
                this.labRoleAddShow.Text = "请双击选择需在修改的角色！";
                return;
            }
            string roleName = this.txtRoleAddName.Text.Trim();
            if (roleName == "")
            {
                this.labRoleAddShow.Text = "请填写角色名称！";
                this.txtRoleAddName.Focus();
                return;
            }
            DataSet ds = bll_CommonPub.GetDataSet("TRoles", "Role_name='" + roleName + "' AND Role_id!='" + _Roleid + "' ");
            int count = 0;
            if (ds.Tables[0].Rows.Count > 0)
            {
                count = ds.Tables[0].Rows.Count;
            }
            if (count > 0)
            {
                this.labRoleAddShow.Text = "角色名称已存在！";
                this.txtRoleAddName.Focus();
                return;
            }
            entity.Role_name = roleName;
            entity.Description = txtRoleAddMark.Text.Trim();
            if (MessageClass.enquire("确认修改信息！") == DialogResult.OK)
            {
                if (bll_TRoles.Update(entity))
                {
                    MessageClass.right("成功！");
                    btnRoleClear_Click(sender, e);
                }
                else
                {
                    MessageClass.error("失败！");
                }
            }
        }
        #endregion

        #region 重置
        private void btnRoleClear_Click(object sender, EventArgs e)
        {
            this._Roleid = 0;
            this.txtRoleAddName.Text = "";
            this.txtRoleAddMark.Text = "";
            this.labRoleAddShow.Text = "提示信息！";
            this.DBind();
        }
        #endregion

        #region 删除角色
        private void btnRoleDelete_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("删除")) return;
            if (_Roleid > 0)
            {
                //需判断是否引用才能删除
                DataSet ds = new DataSet();
                if (bll_CommonPub.GetDataSet("TUserRoleRelation", "Role_id='" + _Roleid + "'") != null)
                {
                    MessageClass.warning("已分配用户,不能删除！");
                    return;
                }
                if (bll_CommonPub.GetDataSet("TGroupRoleRelation", "Role_id='" + _Roleid + "'") != null)
                {
                    MessageClass.warning("已分配组别，不能删除！");
                    return;
                }
                if (bll_CommonPub.GetDataSet("TRolePermissionRelation", "Role_id='" + _Roleid + "'") != null)
                {
                    MessageClass.warning("已分配权限，不能删除！");
                    return;
                }
                if (MessageClass.enquire("确认删除！") == DialogResult.OK)
                {
                    if (bll_TRoles.Delete(_Roleid))
                    {
                        MessageClass.right("成功！");
                        btnRoleClear_Click(sender, e);
                    }
                    else
                    {
                        MessageClass.error("失败！");
                    }
                }
            }
        }
        #endregion
        #endregion

        #region 设置权限
        private void btnRolePemsissionSave_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("编辑")) return;

            if (_Roleid == 0) { MessageClass.error("请选择角色！"); return; }
            if (rbALLPermissions.Checked || rbDelALLPermissions.Checked)
            {
                if (rbALLPermissions.Checked)
                {
                    string str = bll_CommonPub.GetTPermissionStr();
                    if (str != "")
                        _RolePemsissionidStr = str;
                }
                if (rbDelALLPermissions.Checked)
                    _RolePemsissionidStr = "";
            }
            else
            {
                if (moudleid == 0) { MessageClass.error("请选择模块权限！"); return; }
                this.GetPermisissionStr();
            }
            if (MessageClass.enquire("确认设置角色权限！") == DialogResult.OK)
            {
                if (bll_TRolePermissionRelation.AddTRolePermissionRelation(_Roleid, _RolePemsissionidStr))
                {
                    MessageClass.right("成功！");
                    this.GetRolePermisissionStr(_Roleid);
                    SystemVariable.Vaidation(SystemVariable.User_ID);
                    if (moudleid > 0)
                        this.treeViewMenuPermissionClik(moudleid);
                    rbALLPermissions.Checked = false;
                    rbDelALLPermissions.Checked = false;
                }
                else
                {
                    MessageClass.error("失败！");
                }
            }
        }

        /// 获取选中权限 
        public void GetPermisissionStr()
        {
            this._RolePemsissionidStr = "";
            this.strNewpers = "";
            if (strOldpers != "")
            {
                string[] arryStrOldpers = strOldpers.Split(',');
                for (int y = 0; y < arryStrOldpers.Length - 1; y++)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i] == arryStrOldpers[y])
                        {
                            list.Remove(list[i]);
                            break;
                        }
                    }
                }
            }

            for (int i = 0; i < dataGridViewMoudlePermisissionList.Rows.Count; i++)
            {
                if ((bool)dataGridViewMoudlePermisissionList.Rows[i].Cells[0].Value)
                {
                    strNewpers += dataGridViewMoudlePermisissionList.Rows[i].Cells[1].Value.ToString() + ",";
                }
            }

            if (strNewpers != "")
            {
                foreach (var item in strNewpers.Split(','))
                {
                    list.Add(item);
                }
            }
            _RolePemsissionidStr = string.Join(",", list.ToArray());
        }

        #endregion

        #region 模块权限事件
        List<string> list;
        private int moudleid = 0;
        private string strOldpers = "";
        private string strNewpers = "";
        private string[] arryPermisission = null;
        private void treeViewMenuPermission_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (_Roleid == 0) { MessageClass.error("未选中角色！"); return; }
            rbALLPermissions.Checked = false;
            rbDelALLPermissions.Checked = false;
            this.GetRolePermisissionStr(_Roleid);
            if (e.Node.LastNode == null)
            {
                moudleid = Convert.ToInt32(e.Node.Name);
                treeViewMenuPermissionClik(moudleid);
            }
        }

        public void treeViewMenuPermissionClik(int moudleid)
        {
            strOldpers = "";
            #region 模块对应所具有权限
            DataSet ds1 = new DataSet();
            ds1 = bll_CommonPub.GetDataSet("SELECT a.ID, '' AS sortID, b.Value FROM  dbo.TPermissions AS a LEFT OUTER JOIN dbo.TDictionary_Category AS b ON a.Type = b.ID WHERE (a.MoudleID = " + moudleid + " ) AND (a.Display = 1)");
            if (ds1.Tables[0].Rows.Count > 0)
            {
                dataGridViewMoudlePermisissionList.DataSource = ds1.Tables[0].DefaultView;
                this.dataGridViewMoudlePermisissionList.ClearSelection();
            }
            else
            {
                DataSet ds2 = bll_CommonPub.GetDataSet("SELECT TOP 1 * FROM DBO.TDictionary_Category WHERE SortID=1  ");
                DataTable dt = new DataTable();
                dt = ds2.Tables[0];
                dt.Rows.Clear();
                this.dataGridViewMoudlePermisissionList.DataSource = dt;
                MessageClass.error("该模块未分配权限！");
                return;
            }
            #endregion

            #region 取值勾选
            DataSet ds3 = new DataSet();
            ds3 = bll_CommonPub.GetDataSet("TPermissions", "moudleid=" + moudleid + " AND Display = 1");
            int id = 0;
            if (ds3.Tables[0].Rows.Count > 0)
            {
                for (int y = 0; y < ds3.Tables[0].Rows.Count; y++)
                {
                    id = Convert.ToInt32(ds3.Tables[0].Rows[y]["ID"].ToString());
                    if (arryPermisission != null)
                    {
                        for (int i = 0; i < arryPermisission.Length - 1; i++)
                        {
                            if (arryPermisission[i] == id.ToString())
                            {
                                dataGridViewMoudlePermisissionList.Rows[y].Cells[0].Value = true;
                                strOldpers += dataGridViewMoudlePermisissionList.Rows[y].Cells[1].Value + ",";
                                break;
                            }
                            else
                            {
                                dataGridViewMoudlePermisissionList.Rows[y].Cells[0].Value = false;
                            }
                        }
                    }
                    else
                    {
                        this.dataGridViewMoudlePermisissionList.Rows[y].Cells[0].Value = false;
                    }
                }
            }
            #endregion
        }

        #region 获取初始权限，List
        public void GetRolePermisissionStr(int roleid)
        {
            list = new List<string>();
            arryPermisission = null;

            DataSet ds_Pemsission = new DataSet();
            ds_Pemsission = bll_CommonPub.GetDataSet("TRolePermissionRelation", "Role_id='" + roleid + "'");
            if (ds_Pemsission.Tables[0].Rows.Count == 0) return;
            string permission_idStr = ds_Pemsission.Tables[0].Rows[0]["Permission_id"].ToString();
            if (permission_idStr != "")
            {
                arryPermisission = permission_idStr.Split(',');
                foreach (var item in permission_idStr.Substring(0, permission_idStr.Length - 1).Split(','))
                {
                    list.Add(item);
                }
            }
        }
        #endregion
        #endregion

        #region 角色菜单事件
        private void treeViewRoleList_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.labRoleAddShow.Text = "提示信息！";
            if (e.Node.Nodes.Count < 0) return;
            this._Roleid = Convert.ToInt32(e.Node.Name);
            this.DBindPermisission();
            this.GetRolePermisissionStr(_Roleid);
            this.moudleid = 0;
            rbALLPermissions.Checked = false;
            rbDelALLPermissions.Checked = false;
            #region  详细信息
            if (_Roleid > 0)
            {
                TRoles_Entity entity = new TRoles_Entity();
                entity = bll_TRoles.GetEntityByID(_Roleid);
                if (entity != null)
                {
                    this.labShowSelectRole.Text = "所选角色:" + entity.Role_name + "";
                    this.txtRoleAddName.Text = entity.Role_name;
                    this.txtRoleAddMark.Text = entity.Description;
                }
                else
                {
                    this.txtRoleAddName.Text = "";
                    this.txtRoleAddMark.Text = "";
                }
            }
            #endregion

            #region 包含用户
            if (_Roleid > 0)
            {
                this._strWhere = "Role_id= '" + _Roleid + "'";
                this.labShowSelectRole.Text = "所选角色:" + e.Node.Text + "";
            }
            else
            {
                this._strWhere = "";
            }
            this.pageControlUserList.Bind();
            #endregion
        }
        #endregion

        #region 全选、反选
        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridViewMoudlePermisissionList.Rows.Count; i++)
            {
                dataGridViewMoudlePermisissionList.Rows[i].Cells[0].Value = true;
            }
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridViewMoudlePermisissionList.Rows.Count; i++)
            {
                dataGridViewMoudlePermisissionList.Rows[i].Cells[0].Value = false;
            }
        }
        #endregion

        #region 移除用户
        private void dataGridViewUserList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                #region 确认删除
                if (e.ColumnIndex != -1 && this.dataGridViewUserList.CurrentCell.ColumnIndex == 0)
                {
                    if (!SystemVariable.VaildationPermission("删除")) return;
                    int uid = Convert.ToInt32(dataGridViewUserList.CurrentRow.Cells["User_id"].Value.ToString());
                    if (uid == 2)
                    {
                        MessageClass.error("此用户不能移除！");
                        return;
                    }
                    if (MessageClass.enquire("确定删除信息！") == DialogResult.OK)
                    {

                        TUserRoleRelation_BLL bll_TUserRoleRelation = new TUserRoleRelation_BLL();
                        if (bll_TUserRoleRelation.Delete(uid, _Roleid))
                        {
                            this.dataGridViewUserList.Rows.RemoveAt(e.RowIndex);
                        }
                        else
                        {
                            MessageClass.error("失败！");
                        }
                    }
                }
                #endregion
            }
        }
        #endregion

        #region 退出
        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }

        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }

        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }
        #endregion
    }
}
